import * as mars3d from "mars3d"
import "./mapCompare.less"
import { handleMinioUrl } from "@mars/utils/minio"
import { throttle } from "lodash"
const Cesium = mars3d.Cesium
const tilePath : string = import.meta.env.VITE_APP_3DTILE_path as string

// 噪声数据管理器类
class NoiseDataManager {
 private tiles3dLayer
 private mapInstance: mars3d.Map

 constructor(map: mars3d.Map) {
  this.mapInstance = map
}

  /**
   * 倾斜摄影 常熟三环
   *
   * @export add3DLayer 倾斜摄影
   * @returns {originalData}
   */
  public async add3DLayer(originalData: string) {
   console.log("add3DLayer======", originalData)
  //  originalData = "2025-04-17_00"
   const originalUrl = prepareLayerUrl("/tileset.json", tilePath + "/" + originalData)
   console.log("originalUrl======", originalUrl)
    this.tiles3dLayer = new mars3d.layer.TilesetLayer({
      name: "常熟三环",
      url: originalUrl,
      maximumScreenSpaceError: 1,
      maxMemory: 2048, // 最大缓存内存大小(MB)
      cullWithChildrenBounds: false,
      skipLevelOfDetail: true,
      preferLeaves: true,
      
      queryParameters: {
        // 可以传自定义url参数，如token等
        token: "mars3d"
      },
      enableDebugWireframe: true, // 是否可以进行三角网的切换显示
      flyTo: false,
      style: {
        color: {
          conditions: [
            ["${ZS0} < 30", "rgb(0,255,81)"],
            ["${ZS0} < 50", "rgb(199,249,83)"],
            ["${ZS0} < 70", "rgb(250,212,0)"],
            ["${ZS0} < 90", "rgb(255,120,0)"],
            ["${ZS0} < 110", "rgb(255,0,0)"],
            ["true", "rgb(199,21,133)"]
          ]
        }
      },
      popup: [
        {
        field: "FLOOR",
        name: "楼层"
        },
        {
        field: "ZS0",
        name: "噪声值"
        }
      ]
    })
    this.mapInstance.addLayer(this.tiles3dLayer)
    
  
    this.tiles3dLayer.readyPromise.then((layer) => {
      console.log("load完成", layer)
      arrLayer.push(this.tiles3dLayer)
    })
  
  }
}

// 全局变量
let map: mars3d.Map
let mapEx: mars3d.Map
let centerDiv: HTMLElement
const arrLayer: any = []
const arrLayerEx: any = []

// 噪声数据管理器实例
let mapNoiseManager: NoiseDataManager
let mapExNoiseManager: NoiseDataManager

// 初始化当前业务
export function onMounted(mapInstance: mars3d.Map): void {
  map = mapInstance
  map.control.locationBar.enabled = false

  // 双屏对比实现
  const marsDiv = document.getElementById("mars-main-view")
  const centerDivEx = mars3d.DomUtil.create("div", "", marsDiv)
  centerDivEx.setAttribute("id", "centerDivEx")
  centerDivEx.style.display = "block"
  const mars3dContainerEx = mars3d.DomUtil.create("div", "mars3d-container", centerDivEx)
  mars3dContainerEx.setAttribute("id", "mars3dContainerEx")

  centerDiv = document.getElementById("centerDiv")
  centerDiv.style.right = "-50%"
  const center: HTMLElement = map.container
  center.style.width = "50%"

  // 主地图视觉优化
  map.scene.globe.baseColor = Cesium.Color.WHITE
  map.scene.globe.undergroundColor = Cesium.Color.WHITE.withAlpha(0.5)
  map.scene.globe.enableLighting = true
  map.scene.globe.dynamicAtmosphereLighting = true
  map.scene.light = new Cesium.DirectionalLight({
    direction: new Cesium.Cartesian3(0.354925, -0.890918, -0.283358),
    intensity: 2.0
  })

  const mapOptions2 = map.toJSON()
  mapOptions2.control.sceneModePicker = false

  // 对比地图配置
  mapEx = new mars3d.Map(mars3dContainerEx, mapOptions2)
  
  // 对比地图视觉优化（与主地图一致）
  mapEx.scene.globe.baseColor = Cesium.Color.WHITE
  mapEx.scene.globe.undergroundColor = Cesium.Color.WHITE.withAlpha(0.5)
  mapEx.scene.globe.enableLighting = true
  mapEx.scene.globe.dynamicAtmosphereLighting = true
  mapEx.scene.light = new Cesium.DirectionalLight({
    direction: new Cesium.Cartesian3(0.354925, -0.890918, -0.283358),
    intensity: 2.0
  })

  // 初始化噪声数据管理器
  mapNoiseManager = new NoiseDataManager(map)
  mapExNoiseManager = new NoiseDataManager(mapEx)
  
  // 事件监听
  // 优化渲染设置
  map.scene.requestRenderMode = true
  map.scene.maximumRenderTimeChange = Infinity // 禁用自动渲染
  map.scene.globe.showGroundAtmosphere = false // 禁用地面大气效果
  map.scene.fog.enabled = false // 禁用雾效
  map.scene.skyAtmosphere.show = false // 禁用天空大气
  map.scene.debugShowFramesPerSecond = false // 显示FPS用于调试

  mapEx.scene.requestRenderMode = true
  mapEx.scene.maximumRenderTimeChange = Infinity
  mapEx.scene.globe.showGroundAtmosphere = false
  mapEx.scene.fog.enabled = false
  mapEx.scene.skyAtmosphere.show = false



  // 设置更宽松的相机变化阈值
  map.camera.percentageChanged = 0.01
  mapEx.camera.percentageChanged = 0.01
  // 禁用不必要的惯性效果
  map.scene.screenSpaceCameraController.enableTranslate = false
  mapEx.scene.screenSpaceCameraController.enableTranslate = false

  map.setCameraView({ lat: 31.560017, lng: 120.731541, alt: 10985.9, heading: 359.9, pitch: -55.5 })
  mapEx.setCameraView({ lat: 31.560017, lng: 120.731541, alt: 10985.9, heading: 359.9, pitch: -55.5 })
  // 初始同步
  setTimeout(() => {
    // 初始同步时不触发事件
    isSyncing = true
    const initView = map.getCameraView()
    mapEx.setCameraView(initView, {
      duration: 0,
      complete: () => {
        isSyncing = false
        // 启用事件监听
        map.on(mars3d.EventType.cameraChanged, mapExtentChange)
        mapEx.on(mars3d.EventType.cameraChanged, mapExExtentChange)
      }
    })
  }, 300)

}


// 释放当前业务
export function onUnmounted(): void {
  // 移除事件监听
  map.off(mars3d.EventType.cameraChanged, mapExtentChange)
  mapEx.off(mars3d.EventType.cameraChanged, mapExExtentChange)

   // 释放所有图层资源
   arrLayer.forEach((layer: mars3d.layer.BaseLayer) => {
    if (layer.isAdded) {
      map.removeLayer(layer, true) // true表示同时销毁图层
    }
  })
  
  arrLayerEx.forEach((layer: mars3d.layer.BaseLayer) => {
    if (layer.isAdded) {
      mapEx.removeLayer(layer, true)
    }
  })

  // 清空图层数组
  arrLayer.length = 0
  arrLayerEx.length = 0

  // 释放噪声数据管理器
  mapNoiseManager = null
  mapExNoiseManager = null

  // 恢复DOM样式
  const centerDivDom: HTMLElement = map.container
  centerDivDom.style.height = "100%"
  centerDivDom.style.width = "100%"
  centerDivDom.style.right = "0"
  centerDiv.style.right = "0"

  // 移除创建的DOM元素
  const creatDom: HTMLElement = document.getElementById("centerDivEx")
  creatDom.remove()
  // 5. 销毁地图实例
  if (map) {
    map = null
  }
  
  if (mapEx) {
    mapEx = null
  }

  if (syncAnimationFrameId) {
    cancelAnimationFrame(syncAnimationFrameId)
    syncAnimationFrameId = null
  }
}


// 同步控制变量
let isSyncing = false
let syncAnimationFrameId: number | null = null
let lastSyncTime = 0
const SYNC_THROTTLE_TIME = 16 // 约60fps的帧间隔(16ms)

// 优化后的同步函数
function syncCameraViews(sourceMap: mars3d.Map, targetMap: mars3d.Map) {
  // 节流控制：确保同步间隔不小于16ms
  const now = performance.now()
  if (now - lastSyncTime < SYNC_THROTTLE_TIME) {
    if (syncAnimationFrameId) {
      cancelAnimationFrame(syncAnimationFrameId)
    }
    syncAnimationFrameId = requestAnimationFrame(() => syncCameraViews(sourceMap, targetMap))
    return
  }
  lastSyncTime = now

  // 如果正在同步中，则跳过
  if (isSyncing) { return }
  isSyncing = true

  // 使用requestAnimationFrame确保在渲染周期内执行
  syncAnimationFrameId = requestAnimationFrame(() => {
    try {
      // 1. 获取源地图的当前相机状态
      const camera = sourceMap.camera
      const position = camera.position
      const heading = camera.heading
      const pitch = camera.pitch
      const roll = camera.roll

      // 2. 临时禁用目标地图的事件监听
       targetMap.off(mars3d.EventType.cameraChanged, targetMap === mapEx ? mapExExtentChange : mapExtentChange)

      // 3. 直接设置相机参数，跳过动画计算
      targetMap.camera.setView({
        destination: position,
        orientation: {
          heading,
          pitch,
          roll
        }
      })

      // 4. 强制立即渲染
      targetMap.scene.requestRender()

    } catch (e) {
      console.error("同步视图出错:", e)
    } finally {
      // 5. 重新启用事件监听
      targetMap.on(mars3d.EventType.cameraChanged, targetMap === mapEx ? mapExExtentChange : mapExtentChange)
      isSyncing = false
      syncAnimationFrameId = null
    }
  })
}


// 地图事件处理函数（添加防抖）
const mapExtentChange:any = throttle(() => {
  if (!isSyncing) { syncCameraViews(map, mapEx) }
}, SYNC_THROTTLE_TIME)

const mapExExtentChange:any = throttle(() => {
  if (!isSyncing) { syncCameraViews(mapEx, map) }
}, SYNC_THROTTLE_TIME)


// 导出管理器以便外部调用
export function getMapNoiseManager(): NoiseDataManager {
  return mapNoiseManager
}

export function getMapExNoiseManager(): NoiseDataManager {
  return mapExNoiseManager
}

  /**
   * 准备图层URL
   */
function prepareLayerUrl(data: string, path?:string): string {
  // 这里可以添加URL处理逻辑
  return data.startsWith("http") || data.startsWith("https") ? data : handleMinioUrl(path + data)
}
